package com.sakura.oj.controller;

import com.sakura.oj.common.BaseResponse;
import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.common.ResultUtils;
import com.sakura.oj.exception.BusinessException;
import com.sakura.oj.model.dto.auth.AuthRequest;
import com.sakura.oj.model.dto.user.UserRegisterRequest;
import com.sakura.oj.model.vo.LoginUserVO;
import com.sakura.oj.service.AuthStrategy;
import com.sakura.oj.service.UserService;
import com.sakura.oj.utils.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 系统认证接口
 * 负责系统的认证和注册
 *
 * @author Sakura
 */
@RestController
@RequestMapping("auth")
public class AuthController {

    // region 登录相关
    @Resource
    private UserService userService;

    /**
     * 用户登录
     *
     * @param authRequest 认证请求数据
     * @return {@link String} 返回登录成功后的token
     */
    @PostMapping("/login")
    public BaseResponse<String> userLogin(@RequestBody AuthRequest authRequest) {
        if (authRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String accessToken = AuthStrategy.login(authRequest);
        return ResultUtils.success(accessToken);
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest {@link UserRegisterRequest}
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    // endregion

    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @return {@link LoginUserVO}
     */
    @GetMapping("/userinfo")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        return ResultUtils.success(UserHolder.getUser());
    }

}
